package com.iwords.android;

import org.apache.http.client.methods.HttpPost;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.Settings;
import android.text.ClipboardManager;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.mobclick.android.MobclickAgent;
import com.mobclick.android.UmengUpdateListener;

/** 程序启动画面。 */
public class Splash extends Activity implements Callback{
	private final int SPLASH_DISPLAY_LENGHT = 2000; // 延迟三秒
	static {
		//AdManager.setAid("3a8f65992a2e5bc7");//爱词
		//AdManager.setAid("a0a1612985eb8233");//广告专家
		//AdManager.setAid("9dd924ee8579a15c");//移民吧
	}
	
	Handler handler;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash);
		this.handler = new Handler(this);
//		DBHelper dbHelper = new DBHelper(this);
//		try{
//			dbHelper.deleteAll();
//		}finally{
//			dbHelper.cleanup();
//		}
		
		MobclickAgent.update(this);
		MobclickAgent.updateAutoPopup= false;
		MobclickAgent.setUpdateListener(new UmengUpdateListener() {
			@Override
			public void onUpdateReturned(int arg) {
				if(arg == 0){// has update
					MobclickAgent.showUpdateDialog(Splash.this);
				}else{//1: // has no update //2: // none wifi //3: // time out
					if (checkNetworkInfo()) {
						boolean canGo = showPayMe();
						if(!canGo) return;
						new Handler().postDelayed(new Runnable() {
							@Override
							public void run() {
								if (neverShowAgain()) {// 如果用户已经设置不再显示帮助，则直接打开背单词
									Intent mainIntent = new Intent(Splash.this, IWords.class);
									Splash.this.startActivity(mainIntent);
								} else {// 否则，显示帮助
									Intent beginIntent = new Intent(Splash.this, GuideBeginIWords.class);
									Splash.this.startActivity(beginIntent);
								}
							}
						}, SPLASH_DISPLAY_LENGHT);
					}						
				}
			}
		});
	}
	
	public void copyQQ(View v){
		this.vibrate();
		ClipboardManager clipboardManager  = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
		clipboardManager.setText(((TextView)this.findViewById(R.id.qq_number)).getText());
		this.displayMessage("群号已复制到剪贴板。");
	}
	private void vibrate(){
		Vibrator mVibrator = (Vibrator)getApplication().getSystemService(android.app.Service.VIBRATOR_SERVICE);
		mVibrator.vibrate(new long[]{50,50},-1);
	}

	private boolean checkNetworkInfo() {
		//if(true) return false;
		ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		// mobile 3G Data Network
		State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
		// txt3G.setText(mobile.toString());
		// wifi
		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
		// txtWifi.setText(wifi.toString());

		// 如果3G网络和wifi网络都未连接，且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接
		if (mobile == State.CONNECTED || mobile == State.CONNECTING)
			return true;
		if (wifi == State.CONNECTED || wifi == State.CONNECTING)
			return true;
		this.showDialog("设备没有连接网络", "设备没有网络连接，不能正常使用软件服务，现在设置网络链接吗？");
		return false;
	}
	
	public void payMe(View v){
		com.mobclick.android.MobclickAgent.onEvent(this, "PayMeClicked");
		Intent intent = new Intent(Splash.this, com.iwords.android.AlipayAdActivity.class);
		startActivity(intent);
	}

	private void showDialog(String title, String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setTitle(title);
		builder.setMessage(msg);
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
			}
		}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				displayMessage("没有网络，本软件无法使用。");
			}
		});
		builder.create().show();
	}

	private boolean neverShowAgain() {
		SharedPreferences settings = getSharedPreferences(GuideBeginIWords.class.getName(), MODE_PRIVATE);
		boolean neverShowAgain = settings.getBoolean("neverShowAgain", false);
		return neverShowAgain;
	}

	private void displayMessage(String message) {
		Toast t1 = Toast.makeText(this, message, Toast.LENGTH_LONG);
		t1.show();
	}

	/**
	 * 从服务器端获取用户信息，判断是否需要显示去除广告按钮。
	 */
	private boolean showPayMe(){
		boolean canGo = true;
		SharedPreferences settings = getSharedPreferences(IWords.class.getName(), MODE_PRIVATE);
		String username = settings.getString("username", null);
		String password = settings.getString("password", null);
		String href = this.getResources().getString(R.string.user_login);
		href += "&username=" + username;
		href += "&password=" + password;
		HttpPost request = new HttpPost(href);
		//System.out.println("Splash.showPayMe()! href=" + href);
		try {
			JSONObject jSONObject = ServerAccessor.access(this, request);
			boolean success = jSONObject.getBoolean("isSuccess");
			if (success) {
				JSONObject defaultValue = (JSONObject) jSONObject.getJSONObject("defaultValue");
				boolean needPay = defaultValue.getBoolean("needPay");
				//System.out.println("Splash.shoPayMe()! currentlib = "+defaultValue.getLong("currentlib"));
				IWordsApp iWordsApp = (IWordsApp) getApplicationContext();
				iWordsApp.setNeedPay(needPay);
				//System.out.println("Splash.shoPayMe()! iWordsApp.isNeedPay()=" + iWordsApp.isNeedPay());
				if(iWordsApp.isNeedPay()){
					handler.sendEmptyMessage(SHOW_PAY_ME);
				}else{
					handler.sendEmptyMessage(HIDE_PAY_ME);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return canGo;
	}
	
	public void onResume() {
		super.onResume(); 
		com.mobclick.android.MobclickAgent.onResume(this);
	}
	
	public void onPause() {
		super.onPause(); 
		com.mobclick.android.MobclickAgent.onPause(this);
	}

	private static final int SHOW_PAY_ME = 1000;
	private static final int HIDE_PAY_ME = 1001;
	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
			case SHOW_PAY_ME: {
				this.findViewById(R.id.go_to_pay).setVisibility(View.VISIBLE);
				break;
			}
			case HIDE_PAY_ME: {
				this.findViewById(R.id.go_to_pay).setVisibility(View.INVISIBLE);
				break;
			}
		}
		return false;
	}

}